import com.mind.jenkins.pipeline.utils.BuildConfig

def call() {
    // properties([
            // parameters([
                    // string(defaultValue: '', description: '', name: 'COMMIT', trim: false),
                    // string(defaultValue: 'pre-release', description: '', name: 'BRANCH', trim: false),
                    // choice(choices: ['EVOFLOW-PRE', 'EVOFLOW-PROD', 'EVOFLOW-DEV'], description: '选择发布环境,默认pre', name: 'ENV'),
                    // choice(choices: ['pre-release', 'release'], description: '选择分支,默认pre-release', name: 'BRANCH'),
            // ])
    // ])

    dockerNode.nodejsBuildDocker {
        BuildConfig buildConfig
        boolean isSuccess = false
        def causes = currentBuild.getBuildCauses()
        def buildUser = causes[0]?.userId ?: 'Unknown'
        echo "Build User: ${buildUser}"
        try {
            // agent {
            //     node {
            //         label 'jenkins-slave'
            //     }
            // }
            if ("${ENV}" == "EVOFLOW-PROD"){
                stage('部署生产之前二次确认') {
                    input(message: "确定发布环境 ${ENV} 的 ${BRANCH}分支？", ok: 'Continue')
                }
            }
            stage('准备拉取代码') {
                //checkout scm
                checkout([
                        $class           : 'GitSCM',
                        branches         : [[name: BRANCH]],
                        userRemoteConfigs: scm.userRemoteConfigs
                ])
            }

            

            echo "当前发布环境：${ENV}, 当前发布分支：${BRANCH} "

            String appname = jobUtil.getAppNameFromJob()
            echo "当前服务名：${appname}"

            Object commitInfo = jobUtil.getCommitInfo()

            String imageAddr = jobUtil.getImageAdd(ENV)

            String imageName
            String coskey
            String nodejsVersion

            if (params.nodejsVersion == null){
                nodejsVersion = "nodejs-v14"
            }else{
                nodejsVersion = params.nodejsVersion
            }



            stage('安装npm依赖') {
            //   sh 'export process.env.CI=false'
                String buildType = params.buildType

                nodejs(nodejsVersion){

                    sh 'npm config set registry http://10.0.5.33:6532/;'
                    if (appname == "mind-people-admin"){
                        sh 'npm install --legacy-peer-deps'
                    }else if (appname == "mind-pc-web"){
                        if (buildType != null && buildType == "onlyUpgradeTips"){
                            return
                        }else{
                            sh 'npm install'
                        }
                    }else if (appname == "mind-sso-web"){
                        sh 'pnpm install'
                    }else if (appname == "mind-approval-web"){
                        sh 'rm -rf node_modules'
                        sh 'yarn install;'
                    }
                    else{
                        sh 'npm install'
                    }
                    
                    if(appname == "mind-data"){ 
                        if(params.ENV == "EVOFLOW-PRE"){
                            sh 'npm run build:pre -- --env.CI=false'
                        }else{
                            sh 'npm run build:prod -- --env.CI=false'
                        }
                        
                    }else if (appname == "mind-links"){
                        sh 'npm run generate'
                    }else if (appname == "mind-doc-for-shimo"){
                        sh 'npm run build'
                        sh 'npm run build:classic'
                        sh 'cp -r _dist/* dist/'
                        sh 'rm -fr build'
                        sh 'mkdir build'
                        sh 'cp -fr dist/* build'
                    }else if (appname == "mind-doc-common-web"){
                        sh 'npm ci --no-optional;'
                        sh 'npm run build'
                    }else if (appname == "mind-approval-web" || appname == "mind-notes-mymind"){
                        sh 'npm run build'
                        sh 'rm -fr build'
                        sh 'mv dist build'
                    }else if (appname == "mind-sso-web"){
                        if(params.ENV == "EVOFLOW-PRE"){
                            sh 'pnpm run build:pre'
                        }else if (params.ENV == "EVOFLOW-PROD"){
                            sh 'pnpm run build:prod'
                        }else{
                            sh 'pnpm run build'
                        }
                    }else if (appname == "mind-open-platform-admin"){
                        if(params.ENV == "EVOFLOW-PRE"){
                            sh 'pnpm run build:pre'
                        }else if (params.ENV == "EVOFLOW-PROD"){
                            sh 'pnpm run build:prod'
                        }else{
                            sh 'pnpm run build'
                        }

                    }else{
                        if(params.ENV == "EVOFLOW-PRE"){
                            sh 'npm run build:pre -- --env.CI=false'
                        }else if (params.ENV == "EVOFLOW-PROD"){
                            sh 'npm run build:prod -- --env.CI=false'
                        }else{
                            sh 'npm run build -- --env.CI=false'
                        }
                    }
                    archiveArtifacts artifacts: 'build/**', allowEmptyArchive: true
                }

            }


            stage('构建镜像') {        
                parallel 'docker': {
                    echo "Build docker image..."
                    imageName = "${imageAddr}/${appname}:${commitInfo.version}"
                    sh '''sed -i "/FROM openresty/a RUN sed -i 's/https/http/' /etc/apk/repositories" ./deploy/Dockerfile'''
                    dockerfile = "./deploy/Dockerfile"
                    currentBuild.description = "发布环境: ${ENV} \n分支名称: ${BRANCH} \n发布用户: ${buildUser} \n镜像版本号: ${commitInfo.version}"
                    script {
                        // 使用 shell 命令检查镜像是否存在
                        def imageExists = sh(script: "docker image ls ${imageAddr}/${appname} | grep ${commitInfo.version} || true", returnStdout: true).trim()
                        if (imageExists) {
                            echo '镜像已存在，跳过构建'
                        } else {
                            // 构建 Docker 镜像
                            jobUtil.buildDockerImage(dockerfile, "", "nodejs", imageName,"")
                        }
                    }
                }, 'cos': {
                     echo "构建文件上传COS中..."
                }
            }

            stage('单元测试') {
                echo "单元测试中...."
            }

            stage('质量检测') {
                echo "SonarScanner质量检查扫描中...."
            }

            stage('应用部署') {
                echo "Build success, Now Callback Cd..."
                String env = params.ENV
                if ( appname == "mind-job-server" ){
                    jobUtil.createBananaBuild(appname, "sts", env, buildUser, coskey, imageName, commitInfo, params.BRANCH)
                }else if (appname == "mind-sync-server" ){
                    jobUtil.createBananaBuild(appname, "cron", env, buildUser, coskey, imageName, commitInfo, params.BRANCH)
                }else{
                    jobUtil.createBananaBuild(appname, "deploy", env, buildUser, coskey, imageName, commitInfo, params.BRANCH)
                }
            }

            stage('预热CDN缓存') {
                // sh "sleep 30"
                echo "Start PreHeat CDN ..."
                String env = params.ENV
                jobUtil.preHeatUrls(appname,env)
                sh "sleep 30"

                // echo "CDN 预热暂时关闭"

            }
        } finally {
            try {
                stage('通知') {
                    echo "通知工作群..."
                    isSuccess = currentBuild.result == null || currentBuild.result == 'SUCCESS'
                    String branch = params.BRANCH
                    String env = params.ENV
                    notifyUtil.notifyApp(jobUtil.getRepoName(), branch, env, isSuccess, buildUser)
                    String buildType = params.buildType
                    if (buildType != null && (buildType == "all" || buildType == "onlyUpgradeTips")){
                        switch(env) {
                            case "EVOFLOW-PRE":
                                sh "curl -X POST https://premind.im30.net/api/versionManage/webUpgrade"
                            break
                            case "EVOFLOW-PROD":
                                sh "curl -X POST https://mind.im30.net/api/versionManage/webUpgrade"
                            break
                        }
                    }

                }
                
            } catch (err) {
                echo err.getMessage()
            }
            // deleteDir()
        }
    }
}